﻿//===============================================================================
// Copyright © 2011 Allen Lee
// This code released under the terms of the MIT License (http://iridescent.codeplex.com/license)
//===============================================================================
using System;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Media.Animation;

namespace Iridescent
{
	public class FadeInWhenLoading : Behavior<FrameworkElement>
	{
		public FadeInWhenLoading()
		{
			// Insert code required on object creation below this point.

			//
			// The line of code below sets up the relationship between the command and the function
			// to call. Uncomment the below line and add a reference to Microsoft.Expression.Interactions
			// if you choose to use the commented out version of MyFunction and MyCommand instead of
			// creating your own implementation.
			//
			// The documentation will provide you with an example of a simple command implementation
			// you can use instead of using ActionCommand and referencing the Interactions assembly.
			//
			//this.MyCommand = new ActionCommand(this.MyFunction);
		}

		protected override void OnAttached()
		{
			base.OnAttached();

			// Insert code that you would want run when the Behavior is attached to an object.
            AssociatedObject.Opacity = 0;
            AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();

			// Insert code that you would want run when the Behavior is removed from an object.
            AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);
		}

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard storyboard = new Storyboard();
            DoubleAnimation animation = new DoubleAnimation
            {
                Duration = TimeSpan.FromMilliseconds(500),
                To = 1.0,
            };
            Storyboard.SetTargetProperty(animation, new PropertyPath(UIElement.OpacityProperty));
            storyboard.Children.Add(animation);
            Storyboard.SetTarget(storyboard, AssociatedObject);
            storyboard.Begin();
        }

		/*
		public ICommand MyCommand
		{
			get;
			private set;
		}
		 
		private void MyFunction()
		{
			// Insert code that defines what the behavior will do when invoked.
		}
		*/
	}
}